package cn.demo.text.editor.strategy.menu.action;

import cn.demo.text.editor.constant.Str;
import cn.demo.text.editor.strategy.format.process.Format;
import cn.demo.text.editor.strategy.format.process.FormatFactory;

import javax.swing.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class SaveAsAction implements Action {


    @Override
    public void operate(JTextArea jta) throws Exception {
        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle(Str.SAVE_AS);
        jfc.showSaveDialog(null);
        File file = jfc.getSelectedFile();
        BufferedWriter bw = null;

        try {
            if (file == null) return;

            FileWriter fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            String jtaText = jta.getText();

            Format format = FormatFactory.getFormat(file.getName().substring(file.getName().lastIndexOf(".")));
            String[] split = jtaText.split("\\r?\\n");
            StringBuilder jtaTextSb = new StringBuilder();
            for (String line : split) {
                String analysis = format.analysis(Str.SAVE_AS, line);
                jtaTextSb.append(analysis).append(Str.Slash_R_Slash_N);
            }
            jtaText = jtaTextSb.toString();

            bw.write(jtaText);
        } finally {
            if (bw != null) bw.close();
        }
    }
}
